package com.kkb.kkbportal.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kkb.kkbcommon.api.ResultCode;
import com.kkb.kkbcommon.exception.Asserts;
import com.kkb.kkbportal.dao.ProjectRegisterDao;
import com.kkb.kkbportal.domain.ProjectInfo;
import com.kkb.kkbportal.domain.ProjectRegister;
import com.kkb.kkbportal.service.ProjectManagementService;
import com.kkb.kkbportal.service.ProjectRegisterService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName ProjectRegisterServiceImpl
 * @Description 项目报名  todo：
 * @Author mzj
 * @Date 2021/8/13
 **/
@Service
public class ProjectRegisterServiceImpl extends ServiceImpl<ProjectRegisterDao, ProjectRegister> implements ProjectRegisterService {

    @Resource
    private ProjectManagementService pmService;

    /**
     * 点击报名发送用户信息到后台
     *
     * @param userId    用户信息
     * @param projectId 项目id
     * @return void
     */
    @Override
    public void register(Long userId, Long projectId) {
        ProjectRegister projectRegister = new ProjectRegister();
        projectRegister.setUserId(userId);
        projectRegister.setProjectId(projectId);
        int insert = baseMapper.insert(projectRegister);
        if (insert == 0) {
            Asserts.fail(ResultCode.FAILED);
        }
    }


    /**
     * 根据项目Id查询报名信息列表
     *
     * @param projectId 项目Id
     * @return ProjectRegister
     */
    @Override
    public List<ProjectRegister> getRegisterProjectInfo(Long projectId) {
        ProjectRegister register = new ProjectRegister();
        register.setProjectId(projectId);
        List<ProjectRegister> list = lambdaQuery().
                eq(ProjectRegister::getProjectId, register.getProjectId()).list();
        return list;
    }

    /**
     * 查询用户已完成项目数
     *
     * @param userId 用户id
     *               项目状态码 0报名中、1进行中、2已完成、3已取消 报名状态(0 未报名，1 报名中，2 已报名
     * @return int
     */
    @Override
    public int completedProjects(Long userId) {
        int finshedNum = 0;
        //构建报名表查询条件
        ProjectRegister register = new ProjectRegister();
        register.setUserId(userId);
        register.setRegisterStatus(2);
        //查询已报名的项目列表
        List<ProjectRegister> list = lambdaQuery()
                .eq(ProjectRegister::getUserId, userId)
                .eq(ProjectRegister::getRegisterStatus, register.getRegisterStatus()).list();
        //循环遍历已报名项目列表
        for (ProjectRegister reg : list) {
            Long projectId = reg.getProjectId();
            //验证项目是否已完成
            ProjectInfo finshed = pmService.finshed(projectId);
            //如果不为空，就加一
            if (ObjectUtil.isNotNull(finshed)) {
                finshedNum++;
            }
        }
        return finshedNum;
    }

}
